const mqtt = require('aliyun-iot-mqtt');
//设备身份信息
var options = {
  productKey: "k1ku0CwxT0w",
  deviceName: "ywbjq003",
  deviceSecret: "13e44f4068c5b2fba2bc88b6fbe524a8",
  host: "iot-06z00frq8umvkx2.mqtt.iothub.aliyuncs.com"
};

//建立MQTT连接
const client = mqtt.getAliyunIotMqttClient(options);
//订阅云端指令Topic
client.subscribe(`/${options.productKey}/${options.deviceName}/user/get`)
client.subscribe(`/sys/${options.productKey}/${options.deviceName}/thing/event/property/post_reply`)
client.on('message', function (topic, message) {
  console.log("topic " + topic)
  console.log("message " + message)
})

setInterval(function () {
  //定时上报数据
  client.publish(`/sys/${options.productKey}/${options.deviceName}/thing/event/property/post`, getPostData(), { qos: 0 });
}, 5 * 1000);


//电池电量 取值范围：0 ~ 100
var batteryLevel = 100;

function getPostData() {
	
	//湿度  取值范围：0 ~ 100
	var currentHumidity = Math.floor((Math.random() * 20) + 60);
	//温度 取值范围：-40.0 ~ 55.0
	var indoorTemperature = Math.floor((Math.random() * 20) + 60);
	//烟雾检测状态  
	var smokeSensorState = 0;//正常
	if(indoorTemperature > 55){
		smokeSensorState = 1;//异常
	}
	
	if(smokeSensorState === 1 ){
		batteryLevel--;
	}

	
  const payloadJson = {
    id: Date.now(),
    version: "1.0",
    params: {
	  CurrentHumidity: currentHumidity,
	  IndoorTemperature: indoorTemperature,
	  SmokeSensorState: smokeSensorState,
	  BatteryLevel: batteryLevel
    },
    method: "thing.event.property.post"

  }
  console.log("payloadJson " + JSON.stringify(payloadJson))
  return JSON.stringify(payloadJson);
}